/* James McTaggart (jcm28) Informatics
Multimedia Communications Technology - 17th May 2007
In making this submission I declare that my work contains no examples
of misconduct, such as plagiarism, collusion, or fabrication of results.
*/

package server;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Timer;

public class RadioServer extends Thread {

	private DatagramSocket serverSocket;
	//private ExecutorService pool;
	private byte[] inData = new byte[60];
	private byte[] outData = new byte[60];
	private int delay;
	private int period;
	private Timer timer;
	
	public RadioServer(int delay, int period) {
		this.delay = delay;
		this.period = period;
		try {
			serverSocket = new DatagramSocket(7778);
			timer = new Timer();
			//pool = Executors.newCachedThreadPool();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		while(true){
			try {
				DatagramPacket inPacket = new DatagramPacket(inData,inData.length);
				serverSocket.receive(inPacket);
				String in = new String(inPacket.getData());
				int no = getMessageID(in); 
				switch(no){
				case 301:
					RadioTimerTask task = new RadioTimerTask(inPacket.getPort(),inPacket.getAddress());
					timer.scheduleAtFixedRate(task, 0, period);		
					break;
				case 302:
					int n = parseRetransmitNo(in);
					if(n!=-1){
						serverSocket.send(ServerProtocol.get402(n,inPacket.getPort(),inPacket.getAddress()));
					}
					break;
				case -1:break;
				default:break;	
				}
				
				//Add a check about teh packet details
				//RadioTask radioTask = new RadioTask(task,delay, period);
				//pool.execute(radioTask);
				Thread.yield();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	private int parseRetransmitNo(String string){
		//According to protocol spec from byte 14-19 should contain the number
		//of the packet to retransmit
		try{
			return Integer.parseInt(string.substring(13, 19));
		}
		catch(NumberFormatException e){
			return -1;
		}
	}
	private int getMessageID(String message) {
		try {
			int id = Integer.parseInt(message.substring(0, 3));
			if (id != 301 && id != 302) {
				return -1;
			}
			return id;
		} catch (NumberFormatException e) {
			return -1;
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		RadioServer server = new RadioServer(1000,500);
		server.start();
	}

}
